//
//  WBNetworkManager.swift
//  weibo
//
//  Created by 李海超 on 2017/5/25.
//  Copyright © 2017年 lihaichao. All rights reserved.
//


/**
 问题：
 
 1，参数为【string：any？】时不能传nil，所以写为any？
 */








import UIKit
//倒入文件夹的名字
import AFNetworking



enum WBHttpMethod{
    case GET
    case POST
}


class WBNetworkManager: AFHTTPSessionManager {

    //accessToken除登录外，所有的请求都需要
    var accessToken:String? = "2.0076DXcF7vBcXE83f9f9349cJVf_xD"
    
    
    //单例
    static let shared = WBNetworkManager()
    
    
    /**
     封装afnetworking的get／post请求
     
     - parameter method:     请求方式：默认为get
     - parameter URLString:  请求url
     - parameter parameters: 请求参数
     - parameter complete:   成功回掉的闭包
     */
    func request(method:WBHttpMethod = .GET,URLString:String,parameters:Any?,complete:@escaping (_ json:Any?,_ IsSuccess:Bool)->()){
       
        let sucess = {(task:URLSessionDataTask?,json:Any?)->() in
            
            complete(json, true)
        }
        
        let failure = {(task:URLSessionDataTask?,error:Error) in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("token过期了")
                // FIXME:发送通知，提醒用户重新登录
            }
            
            print("你的网络不给力\(error)")
            complete(nil, false)
        
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: sucess, failure: failure)
        }else{
            post(URLString, parameters: parameters, progress: nil, success: sucess, failure: failure)
        }
        
    }
    
    //把所有的网络请求参数都拼接accessToken
    
    func accessTokenRequest(method:WBHttpMethod = .GET,URLString:String,parameters:Any?,complete:@escaping (_ json:Any?,_ IsSuccess:Bool)->()){
        
        // FIXME:发送通知，提醒用户登录
        guard accessToken != nil else {
            print("没有token需要登录")
            complete(nil,false)
            return
        }
        
        
        var parameters = parameters as? Dictionary<String,Any?>
        
        if parameters == nil {//如果为nil表示为初始化参数字典
            parameters = [String:Any?]()
            
        }
        
        //拼接accessToken
        parameters?["access_token"]=accessToken
        
        request(URLString: URLString, parameters: parameters, complete: complete)
        
    }
    
}
